<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { Page, useVbenModal } from '@vben/common-ui';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getColorList, doColorDelete, doColorSyncErp, doColorToggleStatus } from '#/api/color';
import { Button, message, Popconfirm ,Tag} from 'ant-design-vue';

import Form from './modules/form.vue';

import { AntPlusOutlined, AntDeleteOutlined } from '@vben/icons';

const params = ref<any>({
  quick_search: '',
});

// 获取选中的行数据
const selectedRows = ref<any>([]);

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.id);
};

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'id',
  order: 'desc',
};

/**
 * 获取同步状态选项
 */
const getSyncErpOptions = () => {
  return [
    {
      color: 'success',
      label: '已同步',
      value: 1,
    },
    { color: 'default', label: '待同步', value: 0 },
  ];
};

// 移除 getIsEnabledOptions，改用 CellSwitch

const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      label: '颜色名称',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入颜色名称',
      },
    },
    {
      component: 'Input',
      fieldName: 'colorGroup*title',
      label: '分组',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入分组名称',
      },
    },
    {
      component: 'Select',
      fieldName: 'is_enabled',
      label: '状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 0 },
        ],
        placeholder: '请选择状态',
      },
    },
    {
      component: 'Input',
      fieldName: 'erp_id',
      label: 'ERPID',
      operator: '=',
      componentProps: {
        allowClear: true,
        placeholder: '请输入ERPID',
      },
    },
    {
      component: 'Select',
      fieldName: 'sync_erp',
      label: '同步ERP',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: getSyncErpOptions(),
        placeholder: '请选择同步状态',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'create_time',
      label: '创建时间',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnEnter: true,
};

const gridOptions: VxeTableGridOptions = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  height: 'auto',
  rowConfig: { useKey: true, keyField: 'id', isHover: true },
  columnConfig: { useKey: true },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues();
        const queryParams = {
          ...params.value,
          page: page.currentPage,
          limit: page.pageSize,
          search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        };

        const { list, total } = await getColorList(queryParams);

        return {
          items: list || [],
          total: total || 0,
        };
      },
    },
    sort: true,
  },
  columns: [
    { type: 'checkbox', width: 60, align: 'center', fixed: 'left' },
    {
      field: 'name',
      minWidth: 160,
      title: '颜色名称',
      sortable: true,
      align: 'center',
    },
    {
      field: 'code',
      width: 160,
      title: '编码',
      sortable: true,
      align: 'center',
    },
    {
      field: 'colorGroup.title',
      minWidth: 160,
      title: '分组',
      sortable: true,
      align: 'center',
    },
    {
      field: 'is_enabled',
      width: 90,
      title: '状态',
      sortable: false,
      align: 'center',
      cellRender: {
        name: 'CellSwitch',
        props: {
          checkedChildren:'',
          unCheckedChildren:'',
        },
        attrs: {
          beforeChange: async (newVal: number, row: any) => {
            try {
              await doColorToggleStatus({ 
                id: row.id, 
                is_enabled: newVal 
              });
              message.success('状态切换成功');
              return true;
            } catch (error) {
              // message.error('状态切换失败');
              return false;
            }
          },
        },
      },
    },
    {
      field: 'erp_id',
      width: 100,
      title: 'ERPID',
      sortable: true,
      align: 'center',
    },
    {
      field: 'kl_id',
      width: 100,
      title: 'KLID',
      sortable: true,
      align: 'center',
    },
    {
      field: 'sync_erp',
      width: 160,
      title: '同步ERP',
      sortable: true,
      align: 'center',
      slots: {
        default: 'sync_erp',
      },
    },
    {
      field: 'createAdmin.realname',
      width: 100,
      title: '创建人',
      sortable: false,
      align: 'center',
    },
    {
      field: 'create_time',
      width: 180,
      title: '创建时间',
      sortable: true,
      align: 'center',
    },
    {
      field: 'update_time',
      width: 180,
      title: '更新时间',
      sortable: true,
      align: 'center',
    },
    {
      field: 'operation',
      title: '操作',
      width: 80,
      align: 'center',
      fixed: 'right',
      slots: {
        default: 'operation',
      },
    },
  ],
  pagerConfig: {
    currentPage: 1,
    pageSize: 30,
    pageSizes: [30,50, 100, 200, 300],
  },
  exportConfig: {},
  toolbarConfig: { custom: true, export: true, refresh: true, resizable: true, search: true, zoom: true },
  id: 'color_list',
  customConfig: {
    storage: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

const gridEvents = {
  checkboxChange: () => {
    selectedRows.value = gridApi.grid.getCheckboxRecords();
  },
  checkboxAll: () => {
    selectedRows.value = gridApi.grid.getCheckboxRecords();
  },
};

/**
 * 新增
 */
const handleCreate = () => {
  formModalApi.setData({ info: {} }).open();
};

/**
 * 编辑
 */
const handleEdit = (row: any) => {
  formModalApi.setData({ info: row }).open();
};

/**
 * 删除
 */
const handleDelete = async (row: any) => {
  try {
    await doColorDelete({ ids: [row.id] });
    message.success('删除成功');
    gridApi.grid.commitProxy('query');
  } catch (error) {
    console.error('删除失败:', error);
  }
};

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择要删除的数据');
    return;
  }
  try {
    await doColorDelete({ ids: getSelectionIds() });
    message.success('删除成功');
    gridApi.grid.commitProxy('query');
  } catch (error) {
    console.error('删除失败:', error);
  }
};

/**
 * 同步到ERP
 */
const handleSyncErp = async (row: any) => {
  try {
    const res = await doColorSyncErp({ id: row.id });
    message.success(res.msg || '同步成功');
    gridApi.grid.commitProxy('query');
  } catch (error) {
    console.error('同步失败:', error);
  }
};

/**
 * 刷新表格
 */
const fetchData = async () => {
  gridApi.grid.commitProxy('query');
};

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  onClosed: () => {
    fetchData();
  },
});
</script>

<template>
  <Page auto-content-height>
    <Grid v-bind="gridEvents">
      <template #toolbar-actions>
        <Button type="primary" @click="handleCreate">
          <AntPlusOutlined />
          新增
        </Button>
      </template>
      
      <template #sync_erp="{ row }">
        <Tag v-if="row.sync_erp == 1 || row.sync_erp === '1'" color="orange">已同步</Tag>
        <Tag v-else>待同步</Tag>
      </template>

      <template #operation="{ row }">
        <Popconfirm
          v-if="row.sync_erp != 1 && row.sync_erp !== '1'"
          title="同步到ERP系统。确定吗？"
          @confirm="handleSyncErp(row)"
        >
          <Button class="mr-2" type="primary" size="small">同步</Button>
        </Popconfirm>
        <!-- <Button class="mr-2" type="link" size="small" @click="handleEdit(row)">编辑</Button>
        <Popconfirm
          title="确定要删除吗？"
          @confirm="handleDelete(row)"
        >
          <Button type="link" size="small" danger>删除</Button>
        </Popconfirm> -->
      </template>
    </Grid>
    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
